//
//  MYCollectionViewLayout.m
//  瀑布流视图
//
//  Created by 梅毅 on 2017/7/31.
//  Copyright © 2017年 my. All rights reserved.
//

#import "MYCollectionViewLayout.h"

@interface MYCollectionViewLayout()

/*存放每一列最大的y值（每一列的高度） */
@property (nonatomic, strong) NSMutableDictionary   *maxYDict;
/**存放所有的布局属性*/
@property (nonatomic, strong) NSMutableArray        *attributeArray;

@end

@implementation MYCollectionViewLayout

#pragma mark - 懒加载
- (NSMutableDictionary *)maxYDict
{
    if (!_maxYDict) {
        _maxYDict = [[NSMutableDictionary alloc] init];
    }
    return _maxYDict;
}
- (NSMutableArray *)attributeArray
{
    if (!_attributeArray) {
        _attributeArray = [[NSMutableArray alloc] init];
    }
    return _attributeArray;
}
#pragma mark - 初始化默认值
- (instancetype)init
{
    self = [super init];
    if (self) {
        _columnMargin = 15;
        _rowMargin = 10;
        _columnCount = 3;
        _sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    }
    return self;
}
//- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
//{
//    return YES;
//}

#pragma mark - 布局每一个IndexPath的位置
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //计算cell的宽
    CGFloat with = (self.collectionView.frame.size.width - self.sectionInset.left - self.sectionInset.right - (_columnCount-1)*_columnMargin) / _columnCount;
    //计算cell的高度（随机数）
    CGFloat height = arc4random() % 180;
    if (height < 60) {
        height = 60;
    }
    
    //找出所有列中高度最短的那一列
    __block NSString *minColumn = @"0";
    //遍历字典
    [self.maxYDict enumerateKeysAndObjectsUsingBlock:^(NSString *column, NSNumber *maxY, BOOL * _Nonnull stop) {
        if ([maxY floatValue] < [self.maxYDict[minColumn] floatValue]) {
            minColumn = column;
        }
    }];
    //计算位置
    CGFloat x = _sectionInset.left + (_columnMargin + with)*[minColumn floatValue];
    CGFloat y = [self.maxYDict[minColumn] floatValue]+_rowMargin;
    self.maxYDict[minColumn] = @(y + height);
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attrs.frame = CGRectMake(x, y, with, height);
    return attrs;
    
}
#pragma mark - 得到所有的布局属性
- (void)prepareLayout
{
    [super prepareLayout];
    //清空最大的Y值
    for (int i = 0; i < _columnCount; i++) {
        NSString *column = [NSString stringWithFormat:@"%d",i];
        self.maxYDict[column] = @(_sectionInset.top);
    }
    [self.attributeArray removeAllObjects];
    
    //获取总共的Item数
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    for (int i = 0; i < count; i++) {
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        [self.attributeArray addObject:attrs];
    }
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return self.attributeArray;
}
- (CGSize)collectionViewContentSize
{
    //默认最大Y值在第0列
    __block NSString *maxColumn = @"0";
    [self.maxYDict enumerateKeysAndObjectsUsingBlock:^(NSString *column, NSNumber *maxY, BOOL * _Nonnull stop) {
        if ([maxY floatValue]> [_maxYDict[maxColumn] floatValue]) {
            maxColumn = column;
        }
    }];
    return CGSizeMake(self.collectionView.frame.size.width, [self.maxYDict[maxColumn] floatValue] + self.sectionInset.bottom);
}
@end
